import axios from 'axios'
import { useUserStore } from '@/store/user'
import { message as mMessage } from '@/libs'

const service = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
service.interceptors.request.use((config) => {
  const userStore = useUserStore()
  // 添加 icode
  config.headers.icode = '9264731276858682'
  if (userStore.token) {
    config.headers.Authorization = `Bearer ${userStore.token}`
  }

  return config
})

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { success, message, data } = response.data
    if (success) {
      return data
    } else {
      // 业务错误
      mMessage('warn', message)
      return Promise.reject(new Error(message))
    }
  },
  (error) => {
    const userStore = useUserStore()
    // token 超时
    if (error?.response?.data?.code === 401) {
      userStore.logout()
    }
    return Promise.reject(error)
  }
)

export default service
